/**
 * 附件上传-前端工具类
 * @author xhe 2019-07-15 v2.8 addUploadFileNewByOption(obj,option)方法扩展后续配置相关属性confData，同时修改回调函数myDisNew返回多对象
 * @author xhe 2019-06-17 v2.7 file-box新增[data-upload-folder]属性
 * @author xhe 2019-03-19 v2.6 新增addUploadFileNewByOption(obj,option)方法
 * @author xhe 2018-12-20 v2.5 uploadNew调整data-file-progress属性，支持[text/layer/bar]三种。同时选择完成图片优先预览本地，再同步上传。
 * @author xhe 2018-10-11 v2.4 uploadNew方法内新增支持附件上传过程中，进行上传进度监控以及进度反馈提示。
 *                              新增 data-file-progress属性，支持网络上传和文件解析的进度；（IE10以下不支持）
 *                              新增前端data-file-max-size限制（此值不能大于portal配置文件内设置的值）（IE10以下不支持）
 * @author xhe 2018-09-29 v2.3 上传方法支持IE10以下版本再无H5情况下，利用jquery.form.js插件进行异步上传。
 * @author xhe 2018-04-18 v2.2 myDisNew方法中回调函数myBack新增返回对象参数(myData);
 * @author xhe 2017-12-19 v2.1 file-box元素新增data-file-type-disable是否禁用验证文件类型属性。和
 * 								配置说明：1）默认未设置/设置false=开启验证，2）设置true=禁用验证（慎用。
 * @author xhe 2017-08-08 v2.0 添加新的上传方式addUploadFileNew(this)（不受限跨域方式）
 * @author xhe 2016-11-17 v1.4 添加fileId全局变量，方便调用页面反显（添加291,295行）
 * @author xhe 2016-04-01 v1.3
 * 			只是优化upLoad方法，在选择完文件后自动触发上传，减少点击成本（隐藏之前的点击上传按钮）。
 * @author xhe 2015-12-20 v1.2
 *          新增有实体简单版上传，补充返回文件选择框中原文件名称。定义html元素fileNameOld，如：span
 *          id="fileUpText_1_fileNameOld"
 */
var fileNameOld = '';
var fno = '';
(function($) {
    $.toolsupload = {
        uploadNew :function(_7){
            uploadNew(_7);// 新版支持跨域上传 2017-08-08
        },
        upload : function(_1) {
            upLoad(_1);
        },// 上传元素加载方法
        uploadSubmit : function(_2) {
            uploadSubmit(_2);
        }
    };

    /**
     * 添加上传表单、相关按钮等元素
     */
    function upLoad(_1) {
        // 1.检验元素
        if ($("#uploadIframe").length < 1) {
            alert("本页面未添加uploadIframe元素");
            return;
        }
        if ($("#uploadIframeDefDiv").length < 1) {
            alert("本页面未添加uploadIframeDefDiv元素");
            return;
        }
        //alert(document.domain);
        //alert(_1.attaDomain);
        if (document.domain.indexOf(_1.attaDomain, 0) < 0) {
            alert("当前访问域[" + document.domain + "]不包含所配置的domain["
                + _1.attaDomain + "]");
            return;
        }

        // 2.初始化对象
        var divObj = $("#uploadIframeDefDiv");
        var idname = "fileUpText_" + _1.fileNum;
        fno = _1.fileNum;
        var picStoreAction = _1.attaServerUrl;// 设置上传地址
        document.domain = _1.attaDomain;// 设置域
        var fileInputObjId="uploadFileInput";
        // alert(divObj+"|"+idname+"|"+_1.fileNum+"|"+picStoreAction+"|"+document.domain+"|"+_1.attaDomain);

        // 3.防止重复，先清空相关元素
        divObj.html("");
        $("#uploadMediaDefForm").remove();
        $("#" + idname + "_a").text("");
        $("#" + idname + "_msg").html('');

        var str = "<form target='uploadIframe' id='uploadMediaDefForm' name='uploadMediaDefForm' action='" + picStoreAction + "' method='POST' enctype='multipart/form-data'>";
        str += "<input type='hidden' name='callback' value='myDis'/><input type='hidden' name='tokenId' value='"+ _1.tokenId + "'/>";
        str += "<input type='hidden' id='idname' name='idname' value='" + idname + "'/>";
        str += "<input type='file' name=\"upload\" style='opacity: 0;filter:alpha(opacity=0);-moz-opacity:0;' id='"+fileInputObjId+"'/>";
        str += "<input type='hidden' id='upload_fileTypes' name='upload_fileTypes' value='"+ _1.fileTypes + "'/>";
        str += "<input type='hidden' id='upload_fileNum' name='upload_fileNum' value='"+ _1.fileNum + "'/>";

        // 4.根据不同浏览器添加上传form的html元素
        try{
            if (getIEVersion().isIE) { // 如果是IE内核浏览器
                str += "</form>";
                divObj.html(str);
            } else { // 其他浏览器
                divObj.append(str);
                divObj.append("</form>");
            }
        }catch(er){
            divObj.append(str);
            divObj.append("</form>");
        }

        // 5.给上传的file按钮添加内容变化change事件；
        $(document).delegate('input[id="'+fileInputObjId+'"]', 'change', function() {

            //5.1先验证是否满足允许的文件类型
            if(!checkFileTypes(idname,fileInputObjId))return;
            //5.2隐藏同级区域里面的选择文件的按钮
            //$("#" + idname + "_subbtn").parent().find('label[for="uploadFileInput"]').hide();
            //5.3触发上传按钮点击事件；
            //$("#" + idname + "_subbtn").show();
            $("#" + idname + "_subbtn").click();
        });

        // 6.显示其他按钮
        //$("#" + idname + "_subbtn").show();
        // alert(divObj.html());
    }

    /**
     * 新版附件上传
     */
    function uploadNew(_7) {
        var browsObject = getIEVersion();//获取浏览器版本信息
        var obj = _7.obj;
        //var fileNum = _7.fileNum;
        var tokenId = _7.tokenId;
        //var idname = "fileUpText_" + fileNum;
        var objFormId = "uploadMediaDefFormNew";
        var picStoreAction = _7.attaServerUrl;// 设置上传地址
        var fileTypes = _7.fileTypes;
        var sysName = _7.sysName;
        var confDataStr = _7.confData;
        var fileInputObjId="uploadFileInputNew";
        if($("#"+fileInputObjId).length>0 && "undefined"!=$("#"+fileInputObjId).html()){
            //console.log('upload warning : ',"page cannot define ID as ["+fileInputObjId+"] element! Need to be removed!");
            $("#"+objFormId).remove();//强行删除
            // return;
        }
        obj.parent().find("form[name='uploadMediaDefForm']").remove();
        var fileBoxObj = obj.parent('[file-box="true"]');

        var fileTypeDisable = fileBoxObj.attr("data-file-type-disable");//是否禁用文件类型验证
        // alert("是否禁用验证："+typeValidEnable);
        var myFileTypeSetVal = fileBoxObj.attr("data-file-type");//自定义上传文件类型
        fileTypes=doNull(myFileTypeSetVal,fileTypes);

        var myFileMaxSizeVal = fileBoxObj.attr("data-file-max-size");//自定义上传文件大小
        myFileMaxSizeVal=doNull(myFileMaxSizeVal,"10");//默认5M
        myFileMaxSizeVal = myFileMaxSizeVal*1024*1024;

        var fileTypeTag = fileBoxObj.attr("data-type-tag");//上传文件组件类型
        var fileUploadFolder = fileBoxObj.attr("data-upload-folder");//上传文件组件类型

        //obj.text("");
        var fileMsgObj = fileBoxObj.find('[file-msg="true"]');
        fileMsgObj.text('');

        var str = "<form id='"+objFormId+"' name='uploadMediaDefForm' style='display: none;'>";
        if(browsObject.isIE && browsObject.ieVerCode<10){
            str = "<form id='"+objFormId+"' name='uploadMediaDefForm' style='opacity: 0;filter:alpha(opacity=0);-moz-opacity:0;height:0px;' enctype='multipart/form-data' method='post'>";
        }
        str += "<input type='hidden' name='upload_fileTypes' value='"+ fileTypes + "'/>";
        str += "<input type='hidden' name='upload_sysName' value='"+ sysName + "'/>";
        str += "<input type='hidden' name='upload_folder' value='"+ fileUploadFolder + "'/>";
        str += "<input type='hidden' name='confData' value='"+ confDataStr + "'/>";

        if("true"==fileTypeDisable) {
            str += "<input type='file' name=\"upload\" style='opacity: 0;filter:alpha(opacity=0);-moz-opacity:0;height:0px;' id='" + fileInputObjId + "'/>";
        }else{
            str += "<input type='file' name=\"upload\"  accept='" + fileTypes + "' style='opacity: 0;filter:alpha(opacity=0);-moz-opacity:0;height:0px;' id='" + fileInputObjId + "'/>";
        }
        str += "</form>";
        obj.after(str);

        var formObj = $("#"+objFormId);
        console.log('upload info : ','upload component loading completed form[#'+objFormId+'],[sysName='+sysName+']');
        console.log('upload info : ','upload file accept ['+fileTypes+']');

        // 5.给上传的file按钮添加内容变化change事件；
        formObj.find('input[id="uploadFileInputNew"]').bind('change', function() {
            //5.1先验证是否满足允许的文件类型
            var fileName = formObj.find('input[type="file"]').val();
            var fileTypes = formObj.find('input[name="upload_fileTypes"]').val();
            var uploadFolder = formObj.find('input[name="upload_folder"]').val();
            var confData = formObj.find('input[name="confData"]').val();
            console.log('upload info : ','upload file selection completed:'+fileName);
            //alert(fileName+"--"+fileTypes);
            // if(isNull(fileTypes)){
            //     fileMsgObj.text("*未设置文件类型参数");
            //     return false;
            // }
            // if(isNull(fileName)){
            //     alert("请选择文件！");
            //     fileMsgObj.text("*未选择文件");
            //     return false;
            // }
            // alert(fileName+"--uploadImg="+fileTypeTag);
            var thisImgObj = null,fileProgressObj=fileBoxObj.find('[file-progress="true"]');
            var fileProgress = fileBoxObj.attr("data-file-progress");
            var fileProgressEnable=false;
            if(fileProgress!=null && fileProgress != undefined) fileProgressEnable=true;//是否开启 进度条监控及显示
            //上传图片时选择完图片就预览本地图，同时注入新进度条 add 20181220
            if("uploadImg"==fileTypeTag){
                try {
                    thisImgObj = fileBoxObj.find('[file-img="true"]');
                    var fileReader = new FileReader();//1.创建一个读取文件的对象
                    fileReader.readAsDataURL(formObj.find("input[type='file']")[0].files[0]); //2.读取文件是需要时间的
                    fileReader.onload = function () {
                        //3.等上一步读完文件之后才 把图片加载到img标签中,再开始上传
                        thisImgObj.attr("src", fileReader.result);
                    }
                    if(fileProgressEnable){
                        if("bar"==fileProgress && fileProgressObj.length==0 && isNull(fileProgressObj.html())){//第一次追加
                            fileBoxObj.css("position","relative");
                            var proWidth =doNull(thisImgObj.css("width"),"120px");
                            thisImgObj.after("<div file-progress='true' class='progress' style='position:absolute;width:"+proWidth+";height:20px;left:0;bottom:0;opacity:0.7;z-index:7;'><div class='progress-bar progress-bar-warning' aria-valuemin='0' aria-valuemax='100' style='width:0%;font-size:10px;'><span>0%</span></div></divfile-progress>");
                        }
                        //设置默认值
                        fileProgressObj = fileBoxObj.find('[file-progress="true"]');
                        fileProgressObj.find(".progress-bar").css("width","0%");
                        fileProgressObj.find("span").text("0%");
                    }
                } catch (e) {
                    console.log('upload error : ',e);
                }
            }
            // if("true"==fileTypeDisable) {fileTypes="";}
            // //没设置此data-file-type-disable属性。或者设置未false，则默认开启验证类型。
            // if(!isNull(fileTypes) && fileTypes.indexOf(getFileType(fileName))<0){
            //     fileMsgObj.text("*只允许上传以（"+fileTypes+"） 结尾的文件");
            //     return false;
            // }
            var thisfileSize = getFileSize(browsObject,formObj.find('input[type="file"]'));
            if(thisfileSize>myFileMaxSizeVal){
                console.log('upload info : 当前文件大小'+getFileSizeText(thisfileSize)+",已超过上限"+getFileSizeText(myFileMaxSizeVal));
                fileMsgObj.text("*文件不能超过"+getFileSizeText(myFileMaxSizeVal));
                if("uploadImg"==fileTypeTag && fileProgressEnable && "bar"==fileProgress && fileProgressObj){
                    fileProgressObj.find(".progress-bar").css({"width":"100%"});
                    fileProgressObj.find("span").text("上传失败:大小不能超过"+getFileSizeText(myFileMaxSizeVal));
                    obj.text("重新选择");
                }
                return false;
            }
            if(browsObject.isIE && browsObject.ieVerCode<10){
                //不支持html5的IE10以下浏览器
                console.log('upload info : ','the browser\'s current version is ['+browsObject.ieVer+'], But before IE10 browser needs to use [jquery.form.js]');
                var ajax_option = {type:"post",url:picStoreAction,
                    success:function(myData){
                        var objData = JSON.parse(myData);
                        console.log('upload success : ',objData);
                        myDisNew(obj,objData);
                        //myDis(obj.id, obj.flag, obj.msg, obj.murl);
                        formObj.remove();
                    }}
                try{
                    $("#"+objFormId).ajaxSubmit(ajax_option);
                }catch(e){
                    console.log(e);
                    console.log('请检查[jquery.form.js]文件是否在common-base中引用');
                }
            }else{
                //非I及IE10以上的浏览器 走H5
                var tempSessionId = "file_temp_"+new Date().getTime();
                var formData = new FormData();
                var iof = fileName.lastIndexOf('\\');
                fileNameOld = fileName.substring(iof + 1, fileName.length);
                //准备提交数据
                var fileObj = formObj.find("input[type='file']")[0].files[0];
                formData.append("file",fileObj);
                formData.append("name",fileName);
                formData.append("tempSessionId",tempSessionId);
                formData.append("upload_fileTypes",fileTypes);
                formData.append("upload_sysName",sysName);
                formData.append("upload_folder",uploadFolder);
                formData.append("confData",confData);

                //add 20181011  判断是否开启了，上传进度条的反显监控，上传进度监听方法2，监控服务端解析进度
                var fileProgressTimer=null,fileProgressMsg ="进度 0%",layer_progess_index = null;
                if(fileProgressEnable){
                    console.log("upload file-progress : ",fileProgress);
                    if("layer"==fileProgress){
                        layer_progess_index = layer.msg('<span id="layer-file-progress-confirm" style="font-size:14px;padding:10px;">上传进度 0%</span>', {icon:0,time:false,shade: 0.4,area:['200px','65px']});
                    }else{
                        obj.text(fileProgressMsg);
                    }
                    //循环查看状态方法2，监控服务端解析进度
                    /**
                     fileProgressTimer = setInterval(function(){
                        $.ajax({url: ctx+'/progressServlet',type: 'POST',data: {"tempSessionId": tempSessionId},success: function (progressData) {
                                 // console.log(tempSessionId+" result progress",progressData);
                                var data = JSON.parse(progressData);
                                var progress = parseInt((data.progress / data.size) * 100);
                                if(progress>0){
                                    fileProgressMsg ="解析 "+progress+"%";
                                    if("layer"==fileProgress){
                                        $("#layer-file-progress-confirm").text("正在"+fileProgressMsg);
                                    }else if("bar"==fileProgress && fileProgressObj){
                                        fileProgressObj.find(".progress-bar").css("width",progress+"%");
                                        fileProgressObj.find("span").text(progress+"%");
                                    }else{
                                        obj.text(fileProgressMsg);
                                    }
                                }
                            },
                            error: function(){
                                console.log("progress request error");
                            }
                        });
                    }, 100);
                     **/
                }
                //add 20181011  上传进度监听方法1，监控网络传输
                var xhrOnProgress = function(fun) {
                    xhrOnProgress.onprogress = fun; //绑定监听
                    //使用闭包实现监听绑
                    return function () {
                        //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
                        var xhr = $.ajaxSettings.xhr();
                        //判断监听函数是否为函数
                        if (typeof xhrOnProgress.onprogress !== 'function'){
                            return xhr;
                        }
                        //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
                        if (xhrOnProgress.onprogress && xhr.upload) {
                            xhr.upload.onprogress = xhrOnProgress.onprogress;
                        }
                        return xhr;
                    }
                }

                $.ajax({
                    url: picStoreAction,
                    data: formData,
                    type : "POST",
                    xhr: xhrOnProgress(function(e) {//自定义上传进度监听方法，监控网络传输
                        // console.log("percent",e);
                        if(fileProgressEnable){
                            var progress = ((e.loaded / e.total)* 100).toFixed(0);//计算百分比,保留0位小数
                            fileProgressMsg ="上传 "+progress+"%";
                            if("layer"==fileProgress){
                                $("#layer-file-progress-confirm").text("正在"+fileProgressMsg);
                            }else if("bar"==fileProgress && fileProgressObj){
                                fileProgressObj.find(".progress-bar").css("width",progress+"%");
                                fileProgressObj.find("span").text(progress+"%");
                            }else{
                                obj.text(fileProgressMsg);
                            }
                        }

                    }),
                    processData : false, // 告诉jQuery不要去处理发送的数据
                    contentType : false,// 告诉jQuery不要去设置Content-Type请求头
                    success: function(myData){
                        var objData = JSON.parse(myData);
                        console.log('upload success : ',objData);
                        if(fileProgressEnable){
                            clearInterval(fileProgressTimer); //上传完成，清除循环事件
                            fileProgressMsg ="文件上传 100%";
                            if("layer"==fileProgress){
                                $("#layer-file-progress-confirm").text(fileProgressMsg);
                                layer.close(layer_progess_index);
                            }else if("bar"==fileProgress && fileProgressObj){
                                fileProgressObj.find(".progress-bar").css("width","100%");
                                fileProgressObj.find("span").text("100%");
                            }else{
                                obj.text(fileProgressMsg);
                            }
                        }
                        myDisNew(obj,objData);
                        //myDis(obj.id, obj.flag, obj.msg, obj.murl);
                        formObj.remove();
                    },
                    error: function(){
                        clearInterval(fileProgressTimer); //操作完成，清除循环事件
                    }
                });
            }

        });
    }

    //校验文件类型
    function checkFileTypes(idname,fileInputObjId){
        var fileTypes = $('#upload_fileTypes').val();
        if(isNull(fileTypes)){
            $("#" + idname + "_msg").text("*未设置文件类型参数");
            return false;
        }
        var fileNamePath = $('#'+fileInputObjId).val();
        if(fileNamePath==undefined || fileNamePath==""){
            $("#" +idname+ "_msg").text("*未选择文件");
            return false;
        }
        if(fileTypes.indexOf(getFileType(fileNamePath))<0){
            $("#" +idname+ "_msg").text("*只允许上传以（"+fileTypes+"） 结尾的文件");
            return false;
        }
        return true;
    }
    //获取文件名称
    function getFileName(tValue){
        var t1 = tValue.lastIndexOf("\\");
        return tValue.substring(t1 + 1);
    }
    //获取文件后缀类型
    function getFileType(tValue){
        var t1 = tValue.lastIndexOf(".");
        return tValue.substring(t1 + 1).toLowerCase();
    }

    /**
     * 开始上传提交
     */
    function uploadSubmit(_2) {
        var uploadP = $("#uploadFileInput");
        if (!uploadP || uploadP.val() == null
            || $.trim(uploadP.val()).length == 0) {
            alert("请选择文件！");
            return;
        } else {
            var filePath = uploadP.val();
            var iof = filePath.lastIndexOf('\\');
            fileNameOld = filePath.substring(iof + 1, filePath.length);
            // 表单提交
            // if($.browser.msie) {
            $("#uploadMediaDefForm").submit();
            // }else{
            // document.getElementById("uploadMediaDefForm").submit();
            // }
        }
    }

})(jQuery);

/**
 * 回调函数（注意，被引入页面最好别又此函数方法）
 */
var fileId = "";
function myDis(id, flag, msg, murl) {
    //alert(id+"|"+flag+"|"+msg+"|"+murl);
    fileId = id;
    if (flag == "T") {
        $("#" + id).val(murl);
        $("#" + id).attr("fno",fno);
        $("#" + id + "_a").attr('href', murl);
        $("#" + id + "_a").text("点击预览");
        $("#" + id + "_msg").html('上传完成');
        $("#" + id + "_subbtn").prev().text("重新上传").show();//拷贝紧邻的前一个同胞元素；
        //$("#" + id + "_subbtn").hide();//
        $("#" + id + "_fileNameOld").text(fileNameOld);
        $("#" + id + "_showImg").attr("src", murl);
        $("#" + id + "_sid").val(msg);
        $("#" + id + "_addItem").show();
        $("#" + id + "_changebtn").text("重新上传");

        if(isExitsFunction("myBack")){
            myBack();// 被集成的页面自己添加
        }

    } else {
        alert(msg);
    }
}
//新上传方式返回处理
function myDisNew(obj,myData){
    //alert(id+"|"+flag+"|"+msg+"|"+murl);
    var id = myData.id;
    var flag = myData.flag;
    var murl = myData.murl;
    var msg = myData.msg;
    var fileNameOld = myData.fileNameOld;
    var fileNo = obj.attr("file-no");
    if(!isNull(fileNo)){
        myData.fileNo = fileNo;//定义的文件编号
    }
    fileId = id;

    var fileBoxObj = obj.parent();
    if(isNull(fileBoxObj.attr("file-box"))){
        fileBoxObj = obj.parent().parent();
    }
    var fileInputObj = fileBoxObj.find('[file-input="true"]');
    var fileImgObj = fileBoxObj.find('[file-img="true"]');
    var fileAObj = fileBoxObj.find('[file-a="true"]');
    var fileMsgObj = fileBoxObj.find('[file-msg="true"]');
    var fileNameOldObj = fileBoxObj.find('[file-name-old="true"]');
    var fileTypeTag = fileBoxObj.attr("data-type-tag");//上传文件组件类型
    if (flag == "T") {
        fileInputObj.val(murl);
        if(fileImgObj.attr("file-img")){
            fileImgObj.attr("src", murl);
            if(fileAObj){
                fileAObj.attr('href', murl);
                fileAObj.text("点击预览");
            }
        }else{
            if(fileAObj){
                fileAObj.attr('href', murl);
                fileAObj.text("点击查看");
            }
        }
        if(fileMsgObj){
            fileMsgObj.html("<i class='fa fa-check'></i>");
        }
        if(fileNameOldObj){
            fileNameOldObj.text(fileNameOld);
        }
        if(isExitsFunction("myBack")){
            //myBack();// 被集成的页面自己添加
            try {
                window["myBack"](obj,myData);
            } catch(e) {console.log("myBack e",e)}
        }else{
            obj.text("重新上传");
        }

    } else {
        if("uploadImg"==fileTypeTag){
            fileImgObj.attr("src", fileImgObj.attr("data-def"));
        }
        alert(msg);
    }
}


/**
 * 为使用上传的jsp提供的通用方法。注意所用页面需要定义
 *  var myAttaServer 、var myAttaDomain
 */
//选择文件执行方法
function addUploadFile(num){
    var attaServerUrl =myAttaServer+"attachment/media/upload.action?isRemote=T";
    //alert("----------"+myAttaServer);
    //alert("addUploadFile----"+myAttaDomain);
    //alert("addUploadFile----"+attaServerUrl);
    $.toolsupload.upload({
        attaDomain:myAttaDomain,
        attaServerUrl:attaServerUrl,
        fileNum:num,
        tokenId:'',
        fileTypes:'.png,.jpeg,.jpg,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.zip,.rar'
    });
}

//新版20170808 选择文件执行方法（不用考虑域名，简版）
function addUploadFileNew(obj){
    try{ctx}catch(e){alert("检测到页面未定义ctx全局变量！"+e);return;}
    try{sysName}catch(e){alert("检测到页面未定义sysName全局变量！"+e);return;}
    var attaServerUrl = ctx+"/uploadServlet?f="+new Date().getTime();
    $.toolsupload.uploadNew({
        attaServerUrl:attaServerUrl,
        obj:$(obj),
        tokenId:'',
        fileTypes:'aplication/*,text/*,image/*',//https://blog.csdn.net/libinemail/article/details/51022922
        sysName:sysName
    });
}
//新版201903,扩展option参数选项
function addUploadFileNewByOption(obj,option){
    try{ctx}catch(e){alert("检测到页面未定义ctx全局变量！"+e);return;}
    var attaServerUrl = ctx+"/uploadServlet?f="+new Date().getTime();
    var uploadUrls = doNull(option.url,attaServerUrl);
    var uploadSysName = doNull(option.sysName,sysName);
    console.log("addUploadFileNew-conf",uploadSysName,uploadUrls,option);
    $.toolsupload.uploadNew({
        obj:$(obj),
        tokenId:'',
        sysName:uploadSysName,
        attaServerUrl:uploadUrls,
        fileTypes:doNull(option.fileTypes,''),
        confData:doNull(option.confData,'')
    });
}
//判断js函数方法是否存在
function isExitsFunction(funcName) {
    try {
        if (typeof(eval(funcName)) == "function") {
            return true;
        }
    } catch(e) {}
    return false;
}
function isNull(str){
    if(null==str||undefined==str){
        return true;
    }
    if(""==str||"null"==str||"undefined"==str||JSON.stringify(str).trim().length==0){
        return true;
    }
}
function doNull(str, defVal){
    if(isNull(str)){
        return defVal;
    }
    return str;
}
//获取浏览器信息
function getIEVersion() {
    var browsObj = {};
    // var browser_name=navigator.appName;
    var userAgent = navigator.userAgent;
    // if(browser_name=="Microsoft Internet Explorer"){
    // console.log(navigator);
    if ((/msie/.test(userAgent.toLowerCase()))|| (/trident/.test(userAgent.toLowerCase())) ) {
        browsObj["isIE"]=true;
        var browser_version=navigator.appVersion;
        var browser_version_code=browser_version.split(";")[1].replace(/[ ]/g,"");
        browsObj["ieVer"]=browser_version_code;
        if(userAgent.toLowerCase().indexOf("msie")>-1){
            browsObj["ieVerCode"]=parseInt(browser_version_code.replace("MSIE",""));
        }else{
            browsObj["ieVerCode"] = userAgent.match(/msie ([\d.]+)/) != null ? userAgent.match(/msie ([\d.]+)/)[1] : userAgent.match(/rv:([\d.]+)/)[1];
        }
    }else{
        browsObj["isIE"]=false;
    }
    browsObj["isFirefox"]=(/firefox/.test(userAgent.toLowerCase()));
    browsObj["isChrome"]=(/chrome/.test(userAgent.toLowerCase()));
    // browsObj["name"]=browser_name;
    browsObj["userAgent"]=userAgent;
    console.log("browser version : ",browsObj);
    return  browsObj;
}

//获取上传文件的大小
function getFileSize(browsObj,fileObj) {
    try {
        var filesize = 0;
        if(!isNull(fileObj.val())){
            if(browsObj.isFirefox || browsObj.isChrome){
                filesize = fileObj[0].files[0].size;
            }else if(browsObj.isIE){
                if(browsObj.ieVerCode>9){
                    filesize = fileObj[0].files[0].size;
                    // var fso = new ActiveXObject("Scripting.FileSystemObject");
                    // filesize = fso.GetFile(filePath).size;
                    // // var obj_img=new Image();
                    // // obj_img.dynsrc=fileObj.val();
                    // // filesize = obj_img.fileSize;
                }
            }
        }
        var filesizeText =getFileSizeText(filesize);
        // alert("filesize：" + filesize+"，filesizeText="+filesizeText);
        return filesize;
    } catch (e) {
        console.error("错误：" + e);
        return -1;
    }
}

//获取文件大小提示
function getFileSizeText(filesize) {
    var filesizeText = filesize+ "Byte";
    if (filesize >= (1024 * 1024 * 1024)) {
        filesizeText = (filesize / (1024 * 1024 * 1024)).toFixed(0) + "GB";
    } else if (filesize >= (1024 * 1024)) {
        filesizeText = (filesize / (1024 * 1024)).toFixed(0) + "MB";
    } else if (filesize >= (1024)) {
        filesizeText = (filesize / (1024)).toFixed(0) + "KB";
    } else {
        filesizeText = filesize+ "Byte";
    }
    return filesizeText;
}